package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.base.Strings;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
public class OrderCheckHandler implements MsgHandler {

    @Autowired
    private OrderService orderService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //反序列化
        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        if (orderCheck == null || Strings.isNullOrEmpty(orderCheck.getOrderNo())) return;
        //查询订单
        String orderNo = orderCheck.getOrderNo();
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getOrderNo, orderNo)
                .eq(OrderEntity::getStatus, VMSystem.ORDER_STATUS_CREATE);
        OrderEntity orderEntity = orderService.getOne(wrapper);
        if (orderEntity == null) return; //订单已经支付

        //超时订单，修改订单状态
        LambdaUpdateWrapper<OrderEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderEntity::getOrderNo, orderNo)
                .set(OrderEntity::getStatus, VMSystem.ORDER_STATUS_INVALID);
        orderService.update(updateWrapper);
    }
}
